public class Test04 {
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode cur = head;
            int length = 0;
            while(cur != null){
                length++;
                cur = cur.next;
            }
            int n = length / k; //需要对n条长度为n的链表进行反转工作

            ListNode dummy = new ListNode();
            ListNode tail = dummy, newhead = dummy;
            cur = head;
            while(n-- > 0){
                int count = k;
                while(count > 0){
                    ListNode curNext = cur.next;
                    if(count == k) newhead = tail;
                    cur.next = newhead.next;
                    newhead.next = cur;
                    if(count == k) tail = cur;
                    cur = curNext;
                    count--;
                }
            }
            tail.next = cur;
            return dummy.next;

        }

}
